import Vue from 'vue'
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const userType = JSON.parse(localStorage.getItem('USER_INFO'))?.value.userType
  document.title = getPageTitle(to.meta.title)

  if (Vue.ls.get('TOKEN')) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const routes = store.getters.permission_routes || []
      if (routes.length > 0) {
        // 非管理员检测是否有权限进入，没有则进入首页
        if (userType !== '666') {
          if (to.meta.roles && to.meta.roles.length && to.meta.roles.includes('member')) {
            next()
          } else {
            next('/')
          }
        } else {
          console.log('33')
          next()
        }
      } else {
        try {
          let arr_roles = []
          if (userType === '666') {
            arr_roles = ['admin']
          } else {
            arr_roles = ['member']
          }
          // 这个是给sidebar组件赋值
          const accessRoutes = await store.dispatch('permission/generateRoutes', arr_roles)
          accessRoutes.push(
            { path: '*', redirect: '/404', hidden: true }
          )
          router.addRoutes(accessRoutes)
          console.log('accessRoutes', accessRoutes)
          next({ ...to, replace: true })
          // const menuList = JSON.parse(localStorage.getItem('MENU_LIST'))?.value.list
          // console.log('menuList', menuList)
          // if (menuList) {
          //   console.log('menuList 转之后', tranListTotreeList(menuList))
          // }
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
